﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BitTorrent.Bencode;
using BitTorrent.Bencode.Collections;

namespace BitTorrent.Extentions {
    internal static class BencodeExtentions {
        /// <summary>
        /// Get optional string from the dictonary, if the requested string is not pressent
        /// an empty string is returned.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="key">The dictonary key</param>
        /// <returns>The string represented by the key or empty string if key not pressent.</returns>
        public static string GetOptionalString(this Dictionary self, string key) {
            if (!self.ContainsKey(key))
                return string.Empty;

            var s = self[key] as ByteString;
            return s == null ? string.Empty : s.String;
        }

        /// <summary>
        /// Get optional integer from the dictonary, if the requested integer is not pressent
        /// -1 is returned.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="key">The dictonary key</param>
        /// <returns>The integer represented by the key or -1 if key not pressent.</returns>
        public static long GetOptionalInteger(this Dictionary self, string key) {
            if (!self.ContainsKey(key))
                return -1;

            var result = self[key] as Integer;
            return result == null ? -1 : result.Value;
        }
    }
}
